package com.bybops.utils;

import com.bybops.R;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.utils.ByteUtils;

import java.util.UUID;

import static com.inuker.bluetooth.library.Constants.REQUEST_SUCCESS;

/**
 * 蓝牙操作的工具类
 */
public class BlueToothUtils {


    public static UUID serviceUuid = UUID.fromString("0000FF50-0000-1000-8000-00805F9B34FB");
    public static UUID characteristicUuid = UUID.fromString("0000FF52-0000-1000-8000-00805F9B34FB");
    public static UUID notifyUuid = UUID.fromString("0000FF51-0000-1000-8000-00805F9B34FB");
    //开锁

    public static byte[] openLockCommand = ByteUtils.stringToBytes("FF0CA2C8DF842D0B125500EF");
    //获取电压、开关状态指令
    public static byte[] getVoltageAndSwitchStatusCommand = ByteUtils.stringToBytes("FF05A301EF");

    /**
     * 连接
     *
     * @param macAddress
     */
    public static void connect(String macAddress, final LockStatusInf statusInf) {
        //判断本机蓝牙是否已经打开
        if (!ClientManager.getClient().isBluetoothOpened()) {
            //本地蓝牙没有打开
            statusInf.openFail("您没有打开蓝牙");
            return;
        }

//        //连接
        BleConnectOptions options = new BleConnectOptions.Builder()
                .setConnectRetry(3)
                .setConnectTimeout(20000)
                .setServiceDiscoverRetry(3)
                .setServiceDiscoverTimeout(10000)
                .build();
        ClientManager.getClient().connect(macAddress, options, new BleConnectResponse() {
            @Override
            public void onResponse(int code, BleGattProfile data) {
                if (code == REQUEST_SUCCESS) {
                    //连接成功
                    statusInf.connectStatus(true);
                } else {
                    //连接失败
                    statusInf.connectStatus(false);
                }
            }
        });
    }

    /**
     * 开锁
     */
    public static void openLock(String stringMac, final LockStatusInf statusInf) {
        final String macAddress = stringToMacFormat(stringMac);
        // 连接
        connect(macAddress, new LockStatusInf() {
            @Override
            public void openLock(boolean isOpenSuccess) {

            }

            @Override
            public void openFail(String msg) {
                statusInf.openFail(msg);
            }

            @Override
            public void currVoltageAndStatus(String voltage, boolean lockStatus) {

            }

            @Override
            public void connectStatus(boolean connected) {
                if (connected){
                    ClientManager.getClient().notify(macAddress, serviceUuid, notifyUuid, new BleNotifyResponse() {
                        @Override
                        public void onNotify(UUID service, UUID character, byte[] value) {
                            //解析推送过来的数据
                            String stringValue = ByteUtils.byteToString(value);
                            //开锁回调  FF05B201EF
                            String lockStatus = stringValue.substring(6, 8);
                            System.out.println("--------------连接解析数据lockStatus：" + lockStatus);
                            switch (lockStatus) {
                                case "01": { //开的状态
                                    statusInf.openLock(true);
                                    break;
                                }
                                case "00": { //关的状态
                                    statusInf.openLock(false);
                                    break;
                                }
                            }
                        }

                        @Override
                        public void onResponse(int code) {

                        }
                    });
                    ClientManager.getClient().write(macAddress, serviceUuid, characteristicUuid, openLockCommand, new BleWriteResponse() {
                        @Override
                        public void onResponse(int code) {
                            System.out.println("--------------连接write： " + code);
                        }
                    });
                }else {
                    statusInf.openFail("蓝牙连接失败");
                }
                //连接状态回调
                statusInf.connectStatus(connected);
            }
        });

    }

    /**
     * 读取锁的状态
     *
     * @param stringMac
     * @return
     */
    public static void readLockStatus(String stringMac, final LockStatusInf statusInf) {
        final String macAddress = stringToMacFormat(stringMac);

        connect(macAddress, new LockStatusInf() {
            @Override
            public void openLock(boolean isOpenSuccess) {

            }

            @Override
            public void openFail(String msg) {
                statusInf.openFail(msg);
            }

            @Override
            public void currVoltageAndStatus(String voltage, boolean lockStatus) {

            }

            @Override
            public void connectStatus(boolean connected) {
                if (connected){

                    ClientManager.getClient().notify(macAddress, serviceUuid, notifyUuid, new BleNotifyResponse() {
                        @Override
                        public void onNotify(UUID service, UUID character, byte[] value) {
                            //解析推送过来的数据
                            String stringValue = ByteUtils.byteToString(value);
                            System.out.println("------------连接: onNotify   " + stringValue);
                            //读取电量、开关状态回调    FF08B507C50001EF
                            String voltage = stringValue.substring(10, 12);
                            String lockStatus = stringValue.substring(12, 14);
                            boolean hasOpen = false;
                            switch (lockStatus) {
                                case "01": { //开的状态
                                    hasOpen = true;
                                   break;
                                }
                                case "00": { //关的状态
                                    hasOpen = false;
                                }
                                break;
                            }
                            statusInf.currVoltageAndStatus(voltage, hasOpen);
                        }

                        @Override
                        public void onResponse(int code) {

                        }
                    });
                    ClientManager.getClient().write(macAddress, serviceUuid, characteristicUuid, getVoltageAndSwitchStatusCommand, new BleWriteResponse() {
                        @Override
                        public void onResponse(int code) {
                            System.out.println("--------------连接write： " + code);
                        }
                    });
                }else {
                    statusInf.openFail("蓝牙连接失败");
                }
                //连接状态回调
                statusInf.connectStatus(connected);
            }
        });
    }

        private static String stringToMacFormat (String StringMac){
            StringBuilder stringBuilder = new StringBuilder(StringMac);
            int length = StringMac.length();
            int insertCnt = length / 2;
            if (length % 2 == 0) {
                insertCnt--;
            }
            for (int i = 1; i <= insertCnt; i++) {
                stringBuilder.insert(i * 2 + i - 1, ":");
            }
            return stringBuilder.toString();
        }

        public interface LockStatusInf {
            /**
             * 是否开锁成功
             * @param isOpenSuccess
             */
            void openLock(boolean isOpenSuccess);

            void openFail(String msg);

            //当前电压  锁的状态
            void currVoltageAndStatus(String voltage, boolean lockStatus);

            void connectStatus(boolean connected);
        }
        /**
         * 获取电量文本百分比
         *
         * @param energy
         * @return
         */
        public static String getEnergyText (String energy){
            String str = "";
            switch (energy) {
                case "00":
                    str = "0%";
                    break;
                case "01":
                    str = "30%";
                    break;
                case "02":
                    str = "70%";
                    break;
                case "03":
                    str = "100%";
                    break;
            }
            return str;
        }

        /**
         * 获取电量文本百分比
         *
         * @param energy
         * @return
         */
        public static int getEnergyResourceId (String energy){
            int mipId = R.mipmap.icon_energy_zero;
            switch (energy) {
                case "00":
                    mipId = R.mipmap.icon_energy_zero;
                    break;
                case "01":
                    mipId = R.mipmap.icon_energy_thirty;
                    break;
                case "02":
                    mipId = R.mipmap.icon_energy_seventy;
                    break;
                case "03":
                    mipId = R.mipmap.icon_energy_hundred;
                    break;
            }
            return mipId;
        }
    }
